<?php
/**
 * Author: 命中水、
 * Date: 2020/6/9 0:10
 * Email: in1993summer@163.com
 */

namespace App\Console\Commands\PushCenter;

use App\Repositories\User\UserRepository;
use App\Repositories\Wx\WxNoticeRepository;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use App\Services\Wechat;

/**
 * Class WxNoticePush
 * @package App\Console\Commands\PushCenter
 */
class SendWxNotice extends Command
{

    protected $signature = 'pushCenter:sendWxNotice';

    protected $description = 'push center create task';

    private $wxNoticeRepository;

    private $userRepository;

    private $wx;

    private $logger;

    /**
     * WxNoticePush constructor.
     * @param WxNoticeRepository $wxNoticeRepository
     */
    public function __construct(WxNoticeRepository $wxNoticeRepository, UserRepository $userRepository)
    {
        parent::__construct();

        $this->wx = new Wechat();

        $this->wxNoticeRepository = $wxNoticeRepository;

        $this->userRepository = $userRepository;

        $this->logger = Log::channel('console');
    }

    /**
     * @throws \Exception
     */
    public function handle()
    {
        foreach ($this->wxNoticeRepository->getUnPushRecord() as $row) {

            try {

                $this->wx->sendWxTplMsg($row->open_id, $row->content, $row->url);

                $this->wxNoticeRepository->updateSend($row->id);

            } catch (\Exception $e) {

                $this->logger->error($this->signature, [$row, $e]);

                $this->error($e->getMessage());
            }
        }

        $this->info($this->signature . ' success！'. (new Carbon())->toDateTimeString());
    }
}
